﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS运单_新增关务车辆信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoGWAddCarInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMStoGWAddCarInfoController(ILogger<TMStoGWAddContainerInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            //_logger = loggerFactory.CreateLogger<TMStoGWAddCarInfoController>();
        }

        /// <summary>
        /// TMS运单_新增关务车辆信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddGWCarInfo([FromBody] TMStoGWAddContainerInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMStoCRMWayBillInfoResponseDto re = new TMStoCRMWayBillInfoResponseDto();
            CRM_CreateFyInfoRequestDto strRequest = new CRM_CreateFyInfoRequestDto();
            string times = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();

            GW_AddCarInfoRequestDto input = new GW_AddCarInfoRequestDto();
            List<GW_AddCarInfo_Data_Dto> input_data = new List<GW_AddCarInfo_Data_Dto>();
            List<GW_AddCarInfo_Detailed_Dto> input_details = new List<GW_AddCarInfo_Detailed_Dto>();
            if (strparm.waybill_no=="")
            {
                strMsg = "物流发运单不能为空，调用失败！";
            }
            try
            {
                if (strMsg=="")
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("waybill_no", strparm.waybill_no);
                    DataTable m_dt = MethodHelp.GetTableInfo("TMS0130", dic,con);
                    if (m_dt.Rows.Count>0)
                    {
                        foreach (DataRow item in m_dt.Rows)
                        {
                            input_data.Add(new GW_AddCarInfo_Data_Dto {
                                COPID = item["factory_code"].ToString(),
                                CLIENTSEQNO = item["deliverno"].ToString(),
                                COPINNCODE="",
                                COPCODE="",
                                ORGNO="",
                                COPSHORTNAME="",
                                CREDITID="",
                                OWNER="",
                                COPFULLNAME="",
                                CHARGEMAN="",
                                CPHONE="",
                                CFAX="",
                                ADDRESS=""
                            });


                            dic = new Dictionary<string, string>();
                            dic.Add("deliverno", item["deliverno"].ToString());
                            DataTable d_dt = MethodHelp.GetTableInfo("TMS0129", dic, con);
                            if (d_dt.Rows.Count>0)
                            {
                                foreach (DataRow row in d_dt.Rows)
                                {
                                    input_details.Add(new GW_AddCarInfo_Detailed_Dto
                                    {
                                        COPID = row["factory_code"].ToString(),
                                        CLIENTSEQNO = row["deliverno"].ToString(),
                                        PLATENUM_INT = row["car_no"].ToString(),
                                        DRIVERNAME = row["driver_name"].ToString(),
                                        PHONE = row["driver_tel"].ToString(),
                                        AFCDATE = row["shipping_date"].ToString(),
                                        CARCUSNO = "",
                                        LOCKNO = "",
                                        CONTAINERNO = row["cabinet_number"].ToString(),
                                        VOYNO= row["six_link"].ToString(),
                                        REMARK = ""
                                    });

                                }                                
                            }
                           
                        }

                        if (input_data.Count > 0&& input_details.Count>0)
                        {
                            input.DATA = input_data;
                            input.DETAILED = input_details;

                            if (input != null)
                            {
                                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                urldic.Add("function_description", "内部: 关务车辆信息同步");//查看URL配置表地址描述
                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                if (url_dt.Rows.Count > 0)
                                {
                                    string jsonText = JsonConvert.SerializeObject(input);
                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                    GW_AddContainerInfoResponseDto psp = JsonConvert.DeserializeObject<GW_AddContainerInfoResponseDto>(reAgv);
                                    if (psp.code >0)
                                    {
                                        strMsg = psp.message;
                                    }
                                }
                            }
                        }
                        else
                        {
                            strMsg = "运单<" + strparm.waybill_no + ">关务明细生成异常！";
                        }
                    }



                   
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
